package com.ekgc.addressbook.controller;



import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ekgc.addressbook.base.config.Result;

import com.ekgc.addressbook.common.Contacts;
import com.ekgc.addressbook.service.impl.ContactService;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/contacts")
public class ContactController {

    private static final Logger log = LoggerFactory.getLogger(ContactController.class);
    @Autowired
    private ContactService contactService;

    @GetMapping
    public Result queryContacts(
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam String phoneNumber,
            @RequestParam (required = false) Integer groupid,
            @RequestParam(required = false) String keyword) {

        int actualGroupId = groupid != null ? groupid : 0; // 如果 groupid 为 null，设置默认值为 0
        IPage<Contacts> page = contactService.queryContacts(pageNo, pageSize, keyword,phoneNumber,actualGroupId);
        List<Contacts> data = page.getRecords();
        Long total = page.getTotal();
        log.info("total:{}", total);

        return Result.ok(data, total);
    }

    @PostMapping("/add")
    public Result addContact(@RequestBody Contacts contacts) {
        boolean success = contactService.addContact(contacts,contacts.getUserId());
        if (success) {
            return Result.ok();
        } else {
            return Result.fail("添加联系人失败，请检查此联系人是否已经存在。");
        }
    }



    // 后端Controller修改：cat：2025/4/25
//    这里是因为前端传过来的数据在请求体里面而不是以请求参数作为实例。所以后端一直获取不到
    @PostMapping("/delete")
    public Result deleteContact(@RequestBody Map<String, Object> params) {
        String phoneNumber = (String) params.get("phoneNumber");
        Integer userId = (Integer) params.get("userId");
        log.info("phoneNumber:{}, userid:{}", phoneNumber, userId);
        boolean success = contactService.deleteContact(phoneNumber, userId);
        return success ? Result.ok() : Result.fail("删除失败");
    }

    @PostMapping("/update")
    public Result updateContact(@RequestBody Contacts contacts) {
        boolean success = contactService.updateContact(contacts);
        if (success) {
            return Result.ok();
        } else {
            return Result.fail("更新联系人失败");
        }
    }

    @PostMapping("/batch-groups")
    public Result updateContactGroups(@RequestBody Map<String, Object> request) {
        try {
            Object contactIdObj = request.get("contactId");
            int contactId;
            if (contactIdObj instanceof Integer) {
                contactId = (Integer) contactIdObj;
            } else if (contactIdObj instanceof String) {
                contactId = Integer.parseInt((String) contactIdObj);
            } else {
                return Result.fail("Invalid contactId type. Expected Integer or String.");
            }

            Object newGroupIdObj = request.get("newGroupId");
            int newGroupId;
            if (newGroupIdObj instanceof Integer) {
                newGroupId = (Integer) newGroupIdObj;
            } else if (newGroupIdObj instanceof String) {
                newGroupId = Integer.parseInt((String) newGroupIdObj);
            } else {
                return Result.fail("Invalid newGroupId type. Expected Integer or String.");
            }

            contactService.updateContactGroup(contactId, newGroupId);
            return Result.ok("Contact group updated successfully");
        } catch (NumberFormatException e) {
            return Result.fail("Failed to convert contactId or newGroupId to integer: " + e.getMessage());
        } catch (Exception e) {
            return Result.fail("Failed to update contact group: " + e.getMessage());
        }
    }


    @PostMapping("/import")
    public Result<Integer> importContacts(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") Integer userId) {

        log.info("接收到文件: {}", file.getOriginalFilename());
        log.info("用户ID: {}", userId);

        try {
            // 参数校验
            if (file == null || file.isEmpty()) {
                return Result.fail("请选择上传的文件");
            }

            if (!file.getOriginalFilename().toLowerCase().endsWith(".csv")) {
                return Result.fail("请上传CSV格式的文件");
            }

            // 调用服务层处理导入
            int successCount = contactService.importContacts(userId, file);

            return Result.ok(successCount);
        } catch (FileSizeLimitExceededException e) {
            return Result.fail("文件大小超过限制");
        } catch (IOException e) {
            log.error("CSV文件解析失败", e);
            return Result.fail("文件解析失败");
        } catch (Exception e) {
            log.error("导入联系人异常", e);
            return Result.fail("导入失败: " + e.getMessage());
        }
    }
}